package com.andyou.modules.sys.web;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.andyou.common.beanvalidator.BeanValidators;
import com.andyou.common.config.Global;
import com.andyou.common.mapper.JsonMapper;
import com.andyou.common.persistence.Page;
import com.andyou.common.utils.DateUtils;
import com.andyou.common.utils.GridVO;
import com.andyou.common.utils.Select2VO;
import com.andyou.common.utils.StringUtils;
import com.andyou.common.utils.excel.ExportExcel;
import com.andyou.common.utils.excel.ImportExcel;
import com.andyou.common.web.BaseController;
import com.andyou.modules.sys.entity.Office;
import com.andyou.modules.sys.entity.Role;
import com.andyou.modules.sys.entity.User;
import com.andyou.modules.sys.service.SystemService;
import com.andyou.modules.sys.service.UserService;
import com.andyou.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 用户Controller
 * 
 * @author lgx
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {

	@Autowired
	private SystemService systemService;
	@Autowired
	private UserService userService;

	@ModelAttribute
	public User get(@RequestParam(required = false) String id) {
		if (StringUtils.isNotBlank(id)) {
			return systemService.getUser(id);
		} else {
			return new User();
		}
	}

	/**
	 * 获取机构信息
	 * 
	 * @param id
	 *            （参数不可空）
	 * @return
	 * @author lgx Date:2016年6月10日；
	 */
	@RequestMapping(value = { "getOfficeByUserId" })
	@ResponseBody
	public Office getOfficeByUserId(String id) {
		User user = new User();
		Office office = new Office();
		user = systemService.getUser(id);
		office = user.getOffice();
		return office;
	}

	/**
	 * 获取用户信息
	 * 
	 * @param id
	 *            （参数不可空）
	 * @return
	 * @author lgx Date:2016年6月10日；
	 */
	@RequestMapping(value = { "getUserByUserId" })
	public String getUserByUserId(String id, HttpServletResponse response) {
		User user = new User();
		user = systemService.getUser(id);
		super.renderString(response, user);
		return null;
	}

	/* @RequiresPermissions("sys:user:view") */
	@RequestMapping(value = { "dialogIndex" })
	public String dialogIndex(User user, Model model) {
		return "modules/sys/dialogIndex";
	}

	/* 导入 */
	@RequestMapping(value = { "exportant" })
	public String exportant() {
		return "modules/sys/exportant";
	}

	/* @RequiresPermissions("sys:user:view") */
	@RequestMapping(value = { "index" })
	public String index(User user, Model model) {
		return "modules/sys/userIndex";
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "list" })
	public String list(User user, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		// Office office = new Office();
		// office.setId(user.getOfficeId());
		// user.setOffice(office);
		// Page<User> page = systemService.findUser(new Page<User>(request,
		// response), user, false);
		// model.addAttribute("page", page);

		return "modules/sys/userList";
	}

	@ResponseBody
	@RequestMapping(value = { "count" })
	public Object count(User user, HttpServletRequest request, HttpServletResponse response) {
		Office office = new Office();
		office.setId(user.getOfficeId());
		user.setOffice(office);
		Page<User> page = systemService.findUser(new Page<User>(request, response), user, false);
		if (page != null)
			return page.getList().size();
		return 0;
	}

	@RequestMapping(value = { "adminList" })
	public String adminList(User user, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		Office office = new Office();
		office.setId(user.getOfficeId());
		user.setOffice(office);
		Role role = new Role();
		if (user.isAdmin()) {
			role.setId(user.getRole().getId());
		} else
			role.setId("1");
		user.setRole(role);
		Page<User> page = systemService.findUser(new Page<User>(request, response), user, false);

		model.addAttribute("page", page);
		return "modules/sys/userList";
	}

	/**
	 * TODO:获取管理员、用户、角色、账套数
	 * 
	 * @author wx
	 * @date 创建时间 2016年10月28日
	 * @version V1.0
	 */
	@ResponseBody
	@RequestMapping(value = { "adminCount" })
	public Object adminCount(User user, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		Map<String, Object> resp = Maps.newHashMap();
		Office office = new Office();
		office.setId(user.getOfficeId());
		user.setOffice(office);
		Role role = new Role();
		if (user.isAdmin()) {
			role.setId(user.getRole().getId());
		} else
			role.setId("1");
		user.setRole(role);
		// 管理员数
		if (!resp.containsKey("adminCount"))
			resp.put("adminCount", systemService.findListCount(user));

		// 用户数
		if (!resp.containsKey("userCount"))
			resp.put("userCount", systemService.findAllCount(new User()));

		// 角色数
		if (!resp.containsKey("roleCount"))
			resp.put("roleCount", systemService.findRoleCount(new Role()));

		// 当前账套拥有权限账套id列表
		// List<String>
		// accounts=UserAccountUtils.getUserPermitAccounts(UserUtils.getUser());

		return resp;
	}

	@RequestMapping(value = { "dialogNotOrgUserList" })
	public String dialogNotOrgUserList(User user,
			@RequestParam(required = false) Boolean doDataFilter, HttpServletRequest request,
			HttpServletResponse response, Model model) {

		if (doDataFilter == null) {
			doDataFilter = true;
		}

		Office office = new Office();
		office.setId(user.getOfficeId());
		user.setOffice(office);

		Page<User> page_ = new Page<User>(request, response);
		page_.setPageSize(8);
		Page<User> page = systemService.findUser(page_, user, doDataFilter);
		model.addAttribute("page", page);
		return "modules/sys/dialogNotOrgUserList";
	}

	@RequestMapping(value = { "dialogUserList" })
	public String dialogUserList(User user, @RequestParam(required = false) Boolean doDataFilter,
			HttpServletRequest request, HttpServletResponse response, Model model) {

		if (doDataFilter == null) {
			doDataFilter = true;
		}

		Office office = new Office();
		office.setId(user.getOfficeId());
		user.setOffice(office);

		Page<User> page_ = new Page<User>(request, response);
		page_.setPageSize(8);
		page_.setIsModifyedPageSize(false);
		Page<User> page = systemService.findUser(page_, user, doDataFilter);
		model.addAttribute("page", page);
		return "modules/sys/dialogUserList";
	}

	@RequestMapping(value = "dialogUserListByAccount")
	public String dialogUserListByAccount(User user, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Page<User> page = new Page<User>(request, response);
		user.setPage(page);
		page.setList(systemService.findAccAccountUser(user));

		model.addAttribute("page", page);
		return "modules/sys/dialogUserListByAccount";
	}

	@ResponseBody
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "listData" })
	public Page<User> listData(User user, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Page<User> page = systemService.findUser(new Page<User>(request, response), user);
		return page;
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "form")
	public String form(User user, Model model) {
		// if (user.getCompany()==null || user.getCompany().getId()==null){
		// user.setCompany(UserUtils.getUser().getCompany());
		// }
		// if (user.getOffice()==null || user.getOffice().getId()==null){
		// user.setOffice(UserUtils.getUser().getOffice());
		// }
		/*
		 * List<AccAccount> userCorpList =
		 * accAccountDao.findAccountByUserAndAccount(null, user.getId());
		 * if(userCorpList!=null&&userCorpList.size()>0) {
		 * user.setAccAccountList(userCorpList); }
		 */
		model.addAttribute("user", user);
		model.addAttribute("allRoles", systemService.findAllRole());
		/*
		 * List<AccAccount> accAccountList =accAccountDao.findList(new
		 * AccAccount());
		 * model.addAttribute("roleCorpList",accAccountDao.findList(new
		 * AccAccount()));
		 */
		return "modules/sys/userForm";
	}

	/**
	 * 根据选择的所属公司异步加载该公司下的角色
	 * 
	 * @param model
	 * @return
	 * @author lgx Date:2016年6月19日；
	 */
	@RequestMapping(value = { "findRoleByCompanyAjax" })
	public String findRoleByCompany(Model model, String companyId, String userId) {
		List<Role> checkRoleList = Lists.newArrayList();

		if (!StringUtils.isBlank(userId)) {
			User user = systemService.getUser(userId);
			if (user != null) {
				checkRoleList = user.getRoleList();
			}
		}

		List<Role> roleList = systemService.findRoleByCompany(companyId, companyId);
		model.addAttribute("allRoles", roleList);
		model.addAttribute("checkRoleList", checkRoleList);

		return "modules/sys/roleByCompanyAjax";
	}

	@RequiresPermissions(value = { "sys:user:edit", "sys:user:create" }, logical = Logical.OR)
	@RequestMapping(value = "save")
	public String save(User user, HttpServletRequest request, Model model,
			HttpServletResponse response, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?userType=" + user.getUserType()
					+ "&repage";
		}
		// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
		user.setCompany(new Office(request.getParameter("company.id")));
		user.setOffice(new Office(request.getParameter("office.id")));
		// 如果新密码为空，则不更换密码
		if (StringUtils.isNotBlank(user.getNewPassword())) {
			user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
		}
		if (!beanValidator(model, user)) {
			return form(user, model);
		}
		if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))) {
			addMessage(model, "保存用户'" + user.getLoginName() + "'失败，登录名已存在");
			return form(user, model);
		}
		
		if (!"true".equals(this.checkNo(user.getNoOld(), user.getNo(), user.getId()))) {
			addMessage(model, "人员代码"+user.getNo()+"已存在");
			return form(user, model);
		}
		
		// // 角色数据有效性验证，过滤不在授权内的角色
		// List<Role> roleList = Lists.newArrayList();
		// List<String> roleIdList = user.getRoleIdList();
		// for (Role r : systemService.findAllRole()) {
		// if (roleIdList.contains(r.getId())) {
		// roleList.add(r);
		// }
		// }
		// user.setRoleList(roleList);

		// 账套数据有效性验证，过滤不在授权内的账套
		/*
		 * List<AccAccount> accountList = Lists.newArrayList(); List<String>
		 * accountIdList = user.getAccAccountIdList(); List<AccAccount>
		 * allAccountList = accAccountDao.findList(new AccAccount()); for
		 * (AccAccount accAccount : allAccountList) { if
		 * (accountIdList.contains(accAccount.getId())) {
		 * accountList.add(accAccount); } } user.setAccAccountList(accountList);
		 */

		// 保存用户信息
		systemService.saveUser(user);
		// 清除当前用户缓存
		if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
			UserUtils.clearCache();
			// UserUtils.getCacheMap().clear();
		}
		addMessage(redirectAttributes, "保存成功");
		// renderStringByJbox(response, "提交成功");
		return "redirect:" + adminPath + "/sys/user/list?userType=" + user.getUserType()
				+ "&repage";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "delete")
	public String delete(User user, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}
		if (UserUtils.getUser().getId().equals(user.getId())) {
			addMessage(redirectAttributes, "删除用户失败, 不允许删除当前用户");
		} else if (User.isAdmin(user.getId())) {
			addMessage(redirectAttributes, "删除用户失败, 不允许删除超级管理员用户");
		} else {
			systemService.deleteUser(user);
			addMessage(redirectAttributes, "删除用户成功");
		}
		return "redirect:" + adminPath + "/sys/user/list?userType=" + user.getUserType()
				+ "&repage";
	}

	/**
	 * 导出用户数据
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "export")
	public String exportFile(User user, HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		try {
			String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<User> page = new Page<User>(request, response, -1);
			page.setPageSize(10000);
			page = systemService.findUser(page, user);

			new ExportExcel("用户数据", User.class).setDataList(page.getList())
					.write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 导入用户数据
	 * 
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "import")
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<User> list = ei.getDataList(User.class);
			for (User user : list) {
				try {
					if ("true".equals(checkLoginName("", user.getLoginName()))) {
						user.setPassword(SystemService.entryptPassword("123456"));
						BeanValidators.validateWithException(validator, user);
						systemService.saveUser(user);
						successNum++;
					} else {
						failureMsg.append("<br/>登录名 " + user.getLoginName() + " 已存在; ");
						failureNum++;
					}
				} catch (ConstraintViolationException ex) {
					failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex,
							": ");
					for (String message : messageList) {
						failureMsg.append(message + "; ");
						failureNum++;
					}
				} catch (Exception ex) {
					failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败："
							+ ex.getMessage());
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条用户" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 下载导入用户数据模板
	 * 
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		try {
			String fileName = "用户数据导入模板.xlsx";
			List<User> list = Lists.newArrayList();
			list.add(UserUtils.getUser());
			new ExportExcel("用户数据", User.class, 2).setDataList(list).write(response, fileName)
					.dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 验证登录名是否有效
	 * 
	 * @param oldLoginName
	 * @param loginName
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "checkLoginName")
	public String checkLoginName(String oldLoginName, String loginName) {
		if (loginName != null && loginName.equals(oldLoginName)) {
			return "true";
		} else if (loginName != null && systemService.getUserByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 验证员工编号是否存在（提供前端异步处理）
	 * @param noOld  旧编号（参数不可空）
	 * @param on 编号（参数不可空）
	 * @param id 唯一标识（参数可空）
	 * @return 
	 * @author lgx
	 * Date:2018年9月7日；
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "checkNo")
	public String checkNo(String noOld,String no,String id){
		//新建情况下
		if (StringUtils.isBlank(id)) {
			if (!userService.checkIsOnlyByNo(no)) {
				return "false";
			}
		}else{
			//修改情况下：如果和就编码一样则不需要验证，不一样则需要验证
			if (!StringUtils.equals(noOld, no) && !userService.checkIsOnlyByNo(no)) {
				return "false";
			}
		}
		
		return "true";
	}

	@RequestMapping(value = "infoIndex")
	public String infoIndex(Model model) {
		return "modules/sys/infoIndex";
	}

	/**
	 * 用户信息显示及保存
	 * 
	 * @param user
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "info")
	public String info(User user, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		if (StringUtils.isNotBlank(user.getName())) {
			if (Global.isDemoMode()) {
				model.addAttribute("message", "演示模式，不允许操作！");
				return "modules/sys/userInfo";
			}
			currentUser.setEmail(user.getEmail());
			currentUser.setPhone(user.getPhone());
			currentUser.setMobile(user.getMobile());
			currentUser.setRemarks(user.getRemarks());
			currentUser.setPhoto(user.getPhoto());
			systemService.updateUserInfo(currentUser);
			model.addAttribute("message", "保存用户信息成功");
		}
		model.addAttribute("user", currentUser);
		model.addAttribute("Global", new Global());
		return "modules/sys/userInfo";
		// model.addAttribute("user", currentUser);
		// model.addAttribute("Global", new Global());
		// return "modules/sys/userInfo";
		// add for lgx 修改为物业用户信息页面
		// return "modules/sys/userInfo_wy";
	}

	/**
	 * 返回用户信息
	 * 
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "infoData")
	public User infoData() {
		return UserUtils.getUser();
	}

	/**
	 * 修改个人用户密码
	 * 
	 * @param oldPassword
	 * @param newPassword
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "modifyPwd")
	public String modifyPwd(String oldPassword, String newPassword, Model model) {
		User user = UserUtils.getUser();
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) {
			if (Global.isDemoMode()) {
				model.addAttribute("message", "演示模式，不允许操作！");
				return "modules/sys/userModifyPwd";
			}
			if (SystemService.validatePassword(oldPassword, user.getPassword())) {
				systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
				model.addAttribute("message", "修改密码成功");
			} else {
				model.addAttribute("message", "修改密码失败，旧密码错误");
			}
		}
		model.addAttribute("user", user);
		return "modules/sys/userModifyPwd";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required = false) String officeId,
			HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<User> list = systemService.findUserByOfficeId(officeId);
		for (int i = 0; i < list.size(); i++) {
			User e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", "u_" + e.getId());
			map.put("pId", officeId);
			map.put("name", StringUtils.replace(e.getName(), " ", ""));
			mapList.add(map);
		}
		return mapList;
	}

	// @InitBinder
	// public void initBinder(WebDataBinder b) {
	// b.registerCustomEditor(List.class, "roleList", new
	// PropertyEditorSupport(){
	// @Autowired
	// private SystemService systemService;
	// @Override
	// public void setAsText(String text) throws IllegalArgumentException {
	// String[] ids = StringUtils.split(text, ",");
	// List<Role> roles = new ArrayList<Role>();
	// for (String id : ids) {
	// Role role = systemService.getRole(Long.valueOf(id));
	// roles.add(role);
	// }
	// setValue(roles);
	// }
	// @Override
	// public String getAsText() {
	// return Collections3.extractToString((List) getValue(), "id", ",");
	// }
	// });
	// }

	/**
	 * 弹出框
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param model
	 * @return （参数不可空）
	 * @author vikingbin Date:2016年11月25日；
	 */
	@ResponseBody
	@RequestMapping(value = { "userBydialogJson" })
	public String dialogByBootstrapTable(User user, HttpServletRequest request,
			HttpServletResponse response, Model model) {

		if (!StringUtils.isBlank(user.getOfficeId())) {
			Office o = new Office();
			o.setId(user.getOfficeId());
			user.setOffice(o);
		}

		Page<User> page = null;
		if (user.isSearchCurrentCompany()) {
			page = systemService.findUser(new Page<User>(request, response, true), user, false);
		} else {
			page = systemService.findUser(new Page<User>(request, response, true), user);
		}

		model.addAttribute("page", page);

		GridVO gridVO = new GridVO();
		gridVO.setRows(page.getList());
		gridVO.setTotal(page.getCount());
		return JsonMapper.getInstance().toJson(gridVO);
	}

	/**
	 * 获取用户列表
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param model
	 * @return （参数是否可空/不可空）
	 * @author vikingbin Date:2017年1月4日；
	 */
	@ResponseBody
	@RequestMapping(value = { "userListJson" })
	public String dialogByBootstrapTable_(User user, HttpServletRequest request,
			HttpServletResponse response, Model model) {

		if (!StringUtils.isBlank(user.getOfficeId())) {
			Office o = new Office();
			o.setId(user.getOfficeId());
			user.setOffice(o);
		}

		Page<User> page = systemService.findUser(new Page<User>(request, response, true), user);
		model.addAttribute("page", page);

		GridVO gridVO = new GridVO();
		gridVO.setRows(page.getList());
		gridVO.setTotal(page.getCount());

		return JsonMapper.getInstance().toJson(gridVO);
	}

	/**
	 * 调用删除用户的方法
	 * 
	 * @param user
	 * @param redirectAttributes
	 * @return （参数是否可空/不可空）
	 * @author vikingbin Date:2017年1月4日；
	 */
	@ResponseBody
	@RequestMapping(value = "deleteAjax")
	public String deleteAjax(User user, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			return "越权操作，只有超级管理员才能修改此数据！";
		}
		if (Global.isDemoMode()) {
			return "演示模式，不允许操作！";
		}
		if (user.isAdmin()) {
			return user.getLoginName() + " 为超级管理员，不可以被删除！";
		}

		if (UserUtils.getUser().getId().equals(user.getId())) {
			addMessage(redirectAttributes, "删除用户失败, 不允许删除当前用户");
		} else if (User.isAdmin(user.getId())) {
			addMessage(redirectAttributes, "删除用户失败, 不允许删除超级管理员用户");
		} else {
			systemService.deleteUser(user);
		}

		return "删除成功";
	}

	/**
	 * 调用批量删除的方法
	 * 
	 * @param ids
	 * @param redirectAttributes
	 * @return （参数是否可空/不可空）
	 * @author vikingbin Date:2017年1月4日；
	 */
	@ResponseBody
	@RequestMapping(value = "batchDelete")
	public String batchDelete(String ids, RedirectAttributes redirectAttributes) {

		if (Global.isDemoMode()) {
			return "演示模式，不允许操作！";
		}

		if (StringUtils.isBlank(ids)) {
			return "没有可以删除的用户id！";
		}

		String[] userIdsArr = ids.split(",");
		List<String> userIdList = Lists.newArrayList();
		userIdList = Arrays.asList(userIdsArr);

		for (String id : userIdList) {
			if ("1".equals(id)) {
				return "批量删除失败，超级管理员不可以被删除！";
			}
		}

		systemService.batchDeleteUser(userIdList);

		return "删除成功";
	}

	/**
	 * 获取用户下拉列表 （返回Select2 json）
	 * 
	 * @return
	 * @author lgx Date:2017年4月2日；
	 */
	@ResponseBody
	@RequestMapping(value = "findUserListBySelect2")
	public String findUserListBySelect2(User user, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		@SuppressWarnings("unchecked")
		List<User> list = (List<User>) UserUtils.getCache("UserListBySelect2"
				+ UserUtils.getUser().getId());

		if (list == null || list.size() == 0) {
			list = systemService.findUser(user);
			UserUtils.putCache("UserListBySelect2" + UserUtils.getUser().getId(), list);
		}

		if (list != null && list.size() > 0) {
			List<Select2VO> select2VOList = Lists.newArrayList();
			Select2VO select2VO = null;

			for (User obj : list) {
				select2VO = new Select2VO();
				select2VO.setId(obj.getId());
				select2VO.setText(obj.getName());
				select2VOList.add(select2VO);
			}
			return JsonMapper.getInstance().toJson(select2VOList);
		}
		return null;
	}
}
